import React, { Component } from 'react';
import fetchJson from '@/utils/fetch';

import Table from '@/components/Table';
import Page from '@/components/Page';
import Dialog from '@/components/Dialog';
import Form from '@/components/Form';

class Car extends Component {
  constructor (...args) {
    super(...args);
    this.state = {
      carList: [],
      page: 1,
      count: 0,
      addDiaShow: false,
      delDiaShow: false,
      modDiaShow: false,
      curID: null,
      curCar: {}
    }
  }
  async componentDidMount () {
    await this.getCars();
  }
  // 获取carlist
  async getCars () {
    let res = await fetchJson(`api/carlist/${this.state.page}`);
    let count = await fetchJson('api/car_page');
    console.log(res);
    await this.setState({carList: res, count});
  }
  // 页码改变
  async pageChange (page) {
    await this.setState({page})
    await this.getCars();
  }
  // 打开关闭dia
  async handleDia (dia, handle, ID) {
    console.log('ID', ID);
    if (ID) {
      this.setState({curID: ID});
      if (dia === 'modDiaShow') {
        // 找到当前的数据
        let car = await fetchJson('api/car/' + ID);
        this.setState({curCar: car});
      }
    }
    this.setState({[dia]: handle});
  }
  // 执行删除操作
  async doDelete () {
    try {
      await fetchJson(`api/car/${this.state.curID}`, {
        method: 'DELETE'
      });
      alert('删除成功');
      this.handleDia('delDiaShow', false, false);
      await this.getCars();
    } catch (e) {
      console.error(e)
    }
  }
  // 执行添加操作
  async doAdd () {
    let form = this.refs.form1.getFormData();
    await fetchJson('api/car', {
      method: 'POST',
      body: form
    });
    alert('添加成功！');
    this.handleDia('addDiaShow', false);
    await this.getCars();
  }
  // 执行修改操作
  async doMod () {
    let form = this.refs.form2.getFormData();
    await fetchJson('api/car/' + this.state.curCar.ID, {
      method: 'POST',
      body: form
    });
    alert('修改成功');
    this.handleDia('modDiaShow', false);
    await this.getCars();
  }
  // 生成特性
  createFeature (arr, type) {
    let result = [];
    arr.forEach((str, index) => {
      result.push({name: 'feature_name', type: 'hidden', value: str});
      type === 'mod' ? (
        result.push({name: 'feature_value', type: 'text', label: str, value: this.state.curCar.features[index][1]})
      ) : (
        result.push({name: 'feature_value', type: 'text', label: str})
      );
    })
    return result;
  }
  render() {
    return (
      <div>
        <button className="btn btn-primary" onClick={this.handleDia.bind(this, 'addDiaShow', true, false)}>添加</button>
        <Table
          fields={[
            {text: '名称', name: 'title'},
            {text: '价格', name: 'price'}
          ]}
          datas={this.state.carList}
          onModify={this.handleDia.bind(this, 'modDiaShow', true)}
          onDelete={this.handleDia.bind(this, 'delDiaShow', true)}
        ></Table>
        <Page
          count={this.state.count}
          cur={this.state.page}
          onChange={this.pageChange.bind(this)}
        ></Page>
        {/* 添加 */}
        {
          this.state.addDiaShow ? (
            <Dialog shadow={true} title="添加" close_btn={true} onClose={this.handleDia.bind(this, 'addDiaShow', false)}>
              <Form
                ref="form1"
                fields={[
                  {name: 'title', type: 'text', label: '车辆标题', placeholder: '请输入车辆标题'},
                  {name: 'price', type: 'text', label: '车辆价格', placeholder: '请输入车辆价格'},
                  {name: 'description', type: 'text', label: '车辆描述', placeholder: '请输入车辆描述'},
                  {name: 'images', type: 'file', label: '车辆图片', isArr: true},
                  ...this.createFeature(['上牌时间', '表显里程', '本车排量', '变速箱', '排放标准', '车辆性质', '车辆颜色', '维修保养', '年检到期', '商业险到期', '交强险到期', '档位个数', '驱动方式', '综合油耗', '车身结构', '发动机缸数', '最大功率', '进气类型'])
                ]}
                btns={[
                  {text: '添加', type: 'primary', onClick: this.doAdd.bind(this)},
                  {text: '取消', type: 'default', onClick: this.handleDia.bind(this, 'addDiaShow', false)}
                ]}
              ></Form>
            </Dialog>
          ) : ''
        }
        {/* 删除 */}
        {
          this.state.delDiaShow ? (
            <Dialog shadow={true} title="警告" close_btn={true} onClose={this.handleDia.bind(this, 'delDiaShow', false)}>
              <p>是否删除该车辆信息(ID: {this.state.curID})</p>
              <div style={{textAlign: 'right'}}>
                <button className="btn btn-danger" onClick={this.doDelete.bind(this)}>删除</button>
                <button className="btn btn-default" onClick={this.handleDia.bind(this, 'delDiaShow', false, false)}>取消</button>
              </div>
            </Dialog>
          ) : ''
        }
        {/* 修改 */}
        {
          this.state.modDiaShow ? (
            <Dialog
              shadow={true} title={'修改 ID:' + this.state.curID} close_btn={true} onClose={this.handleDia.bind(this, 'modDiaShow', false)}
            >
              <Form
                ref="form2"
                fields={[
                  {name: 'title', type: 'text', label: '车辆标题', placeholder: '请输入车辆标题', value: this.state.curCar.title},
                  {name: 'price', type: 'text', label: '车辆价格', placeholder: '请输入车辆价格', value: this.state.curCar.price},
                  {name: 'description', type: 'text', label: '车辆描述', placeholder: '请输入车辆描述', value: this.state.curCar.description},
                  // {name: 'images', type: 'file', label: '车辆图片', isArr: true, counts: this.state.curCar.images.length},
                  // ...this.createFeature(['上牌时间', '表显里程', '本车排量', '变速箱', '排放标准', '车辆性质', '车辆颜色', '维修保养', '年检到期', '商业险到期', '交强险到期', '档位个数', '驱动方式', '综合油耗', '车身结构', '发动机缸数', '最大功率', '进气类型'], 'mod')
                ]}
                btns={[
                  {text: '修改', type: 'primary', onClick: this.doMod.bind(this)},
                  {text: '取消', type: 'default', onClick: this.handleDia.bind(this, 'modDiaShow', false, false)}
                ]}
              ></Form>
            </Dialog>
          ) : ''
        }
      </div>
    );
  }

}

export default Car;
